<?php
namespace App\Service\Admin\Point;

use Illuminate\Support\Facades\DB;

class GoodsService extends BaseService
{
    //商品

    /**
     * 列表
     * @param array $pages【start，limit】
     */
    public function getList($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbEqGoods)->where('del', 0);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有商品');
        }
        $arys = [];
        foreach ($res as $v ) {
            $v = (array) $v;
            $cateOne = (array) $this->dbConn($this->dbEqGcate)
                ->where('del', 0)
                ->where('id', $v['cate_id'])
                ->first();
            $cate_name = !empty($cateOne) ? $cateOne['title'] : '';
            if (file_exists($v['bigimg'])) {
                $imgPrefix = env('DOMAIN') . '/';
            } else {
                $imgPrefix = env('FC_DOMAIN') . '/';
            }
            $arys[] = [
                'id' => $v['id'],
                'gno' => $v['gno'],
                'title' => $v['title'],
                'imgPrefix' =>  $imgPrefix,
                'imgLink' =>  $v['bigimg'],
                'cate_id' => $v['cate_id'],
                'cate_name' => $cate_name,
                'sale' => $v['sale'],
                'isnew' => $v['isnew'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 分类选项
     */
    public function getCateList()
    {
        $arys[] = [ 'id' => 0, 'title' => '-选择分类-' ];
        $res = $this->dbConn($this->dbEqGcate)->where('del', 0)->get();
        if (count($res)) {
            foreach ($res as $v) {
                $v = (array) $v;
                $arys[] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                ];
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 一个
     * @param int $id 商品ID
     */
    public function getOne($id)
    {
        $res = (array) $this->dbConn($this->dbEqGoods)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '没有商品');
        }
        //分类
        $cateOne = (array) $this->dbConn($this->dbEqGcate)
            ->where('del', 0)
            ->where('id', $res['cate_id'])
            ->first();
        $cate_name = !empty($cateOne) ? $cateOne['title'] : '';
        //详情图
        $moreImgs = [];
        $moreImgOnes = $this->dbConn($this->dbEqGimg)
            ->where('del', 0)
            ->where('gid', $res['id'])
            ->get();
        if (count($moreImgOnes)) {
            foreach ($moreImgOnes as $v) {
                $v = (array) $v;
                $moreImgs[] = [
                    'id' => $v['id'],
                    'imgDomain' => file_exists($v['link']) ? env('DOMAIN') . '/' : env('FC_DOMAIN') . '/',
                    'img' => $v['link'],
                    'w' => $v['width'],
                    'h' => $v['height'],
                ];
            }
        }
        //SKU
        $skuLists = [];
        $skuOnes = $this->dbConn($this->dbEqGsku)
            ->where('del', 0)
            ->where('gid', $res['id'])
            ->get();
        if (count($skuOnes)) {
            foreach ($skuOnes as $v) {
                $v = (array) $v;
                $skuLists[] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                    'price' => $v['price'],
                    'price_line' => $v['price_line'],
                    'stock' => $v['stock'],
                ];
            }
        }
        $arys = [
            'id' => $res['id'],
            'title' => $res['title'],
            'imgDomain' => file_exists($res['bigimg']) ? env('DOMAIN') . '/' : env('FC_DOMAIN') . '/',
            'img' => $res['bigimg'],
            'cate_id' => $res['cate_id'],
            'cate_name' => $cate_name,
            'sale' => $res['sale'],
            'detail' => $res['detail'] ? htmlspecialchars_decode($res['detail']) : '',
            'isnew' => $res['isnew'],
            'moreImgs' => $moreImgs,
            'skuLists' => $skuLists,
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 添加
     * @param array $pas
     * @param array $imgs
     * @param array $skus
     */
    public function addOne($pas, $imgs, $skus)
    {
        //添加商品
        $gData = [
            'title' => $pas['title'],
            'gno' => toGno(),
            'cate_id' => $pas['cate_id'],
            'bigimg' => $pas['bigimg'],
            'detail' => $pas['detail'] ? htmlspecialchars($pas['detail']) : '',
            'isnew' => $pas['isnew'],
            'addtime' => toDate(),
            'uptime' => toDate(),
        ];
        DB::beginTransaction(); //开启事务
        try {
            $gid = $this->dbConn($this->dbEqGoods)->insertGetId($gData);
            if (!$gid) {
                return $this->toback(-1, '商品error');
            }
            //添加详情图
            foreach ($imgs as $v) {
                $imgData = [
                    'gid' => $gid,
                    'link' => $v['img'],
                    'width' => $v['w'],
                    'height' => $v['h'],
                    'addtime' => toDate(),
                ];
                $imgup = $this->dbConn($this->dbEqGimg)->insertGetId($imgData);
                if (!$imgup) {
                    return $this->toback(-1, 'img error');
                }
            }
            //添加SKU
            foreach ($skus as $v) {
                $skuData = [
                    'gid' => $gid,
                    'title' => $v['title'],
                    'price' => $v['price'],
                    'price_line' => $v['price_line'],
                    'stock' => $v['stock'],
                    'addtime' => toDate(),
                    'uptime' => toDate(),
                ];
                $skuid = $this->dbConn($this->dbEqGsku)->insertGetId($skuData);
                if (!$skuid) {
                    return $this->toback(-1, 'sku失败');
                }
            }
            DB::commit(); //提交事务
            return $this->toback();
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return $this->toback(-1, 'error');
        }
    }

    /**
     * 多图上传
     * @param int $id 商品ID
     * @param string $img
     * @param int $iw
     * @param int $ih
     */
    public function moreUpload($id, $img, $iw, $ih)
    {
        $total = $this->dbConn($this->dbEqGimg)
            ->where('del', 0)
            ->where('gid', $id)
            ->count();
        if ($total >= 5) {
            return array('code' => -2, 'msg' => '详情最多5张');
        }
        //图片集合
        $this->dbConn($this->dbImg)->insertGetId([
            'link' => $img,
            'width' => $iw,
            'height' => $ih,
            'addtime' => toDate(),
        ]);
        //商品多图
        $this->dbConn($this->dbEqGimg)->insertGetId([
            'gid' => $id,
            'link' => $img,
            'width' => $iw,
            'height' => $ih,
            'addtime' => toDate(),
        ]);
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 多图删除
     * @param int $id 图片ID
     */
    public function moreDel($id)
    {
        $res = (array) $this->dbConn($this->dbEqGimg)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '图片不存在');
        }
        //商品多图
        $this->dbConn($this->dbEqGimg)->where('id', $id)
            ->update([
                'id' => $id,
                'del' => 1,
                'deltime' => toDate(),
            ]);
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 修改
     * @param int $id 商品ID
     * @param array $pas
     */
    public function modify($id, $pas)
    {
        $res = (array) $this->dbConn($this->dbEqGoods)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '商品不存在');
        }
        //修改商品
        $gData = [
            'title' => $pas['title'],
            'cate_id' => $pas['cate_id'],
            'bigimg' => $pas['bigimg'],
            'detail' => $pas['detail'] ? htmlspecialchars($pas['detail']) : '',
            'isnew' => $pas['isnew'],
            'uptime' => toDate(),
        ];
        $gup = $this->dbConn($this->dbEqGoods)->where('id', $id)->update($gData);
        if (!$gup) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code'=>0, 'msg'=>'success');
    }

    /**
     * 删除
     * @param int $id 商品ID
     */
    public function setDel($id)
    {
        $res = (array) $this->dbConn($this->dbEqGoods)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '商品不存在');
        }
        $arys = [
            'del' => 1,
            'deltime' => toDate(),
        ];
        $up = $this->dbConn($this->dbEqGoods)->where('id', $id)->update($arys);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * SKU添加
     * @param array $pas 商品SKU
     */
    public function skuAdd($pas)
    {
        $arys = [
            'gid' => $pas['gid'],
            'title' => $pas['title'],
            'price' => $pas['price'],
            'price_line' => $pas['price_line'],
            'stock' => $pas['stock'],
            'addtime' => toDate(),
            'uptime' => toDate(),
        ];
        $lastid = $this->dbConn($this->dbEqGsku)->insertGetId($arys);
        if (!$lastid) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * SKU修改
     * @param int $id SKU的ID
     * @param array $pas 商品SKU
     */
    public function skuModify($id, $pas)
    {
        $res = (array) $this->dbConn($this->dbEqGsku)->where('del', 0)->where('id', $id)->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该SKU不存在');
        }
        $arys = [
            'title' => $pas['title'],
            'price' => $pas['price'],
            'price_line' => $pas['price_line'],
            'stock' => $pas['stock'],
            'uptime' => toDate(),
        ];
        $up = $this->dbConn($this->dbEqGsku)->where('id', $id)->update($arys);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * SKU删除
     * @param int $id SKU的ID
     */
    public function skuDel($id)
    {
        $res = (array) $this->dbConn($this->dbEqGsku)->where('del', 0)->where('id', $id)->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该SKU不存在');
        }
        $arys = [
            'del' => 1,
            'deltime' => toDate(),
        ];
        $up = $this->db2Conn($this->dbEqGsku)->where('id', $id)->update($arys);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }
}